package com.tj.jinzao.activity;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.PointF;
import android.graphics.Rect;
import android.media.FaceDetector;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.KeyEvent;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;

import com.bumptech.glide.Glide;
import com.tj.jinzao.R;
import com.tj.jinzao.base.BaseActivity;
import com.tj.jinzao.base.IBaseView;
import com.tj.jinzao.common.Constant;
import com.tj.jinzao.easydl.camera.CameraListener;
import com.tj.jinzao.easydl.util.ThreadPoolManager;
import com.tj.jinzao.easydl.view.PreviewView;
import com.tj.jinzao.easydl.view.model.DetectResultModel;
import com.tj.jinzao.model.DetectQuestion;
import com.tj.jinzao.model.FaceResult;
import com.tj.jinzao.presenter.DetectPresenter;
import com.tj.jinzao.utils.ImageUtils;
import com.tj.jinzao.utils.Utils;
import com.tj.jinzao.widgets.ChooseConfigDialog;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;

/**
 * 人脸识别activity
 * Created by wjy on 2018/5/22.
 */

public class FaceDetectActivity extends BaseActivity implements IBaseView<List<DetectQuestion>> {

    @BindView(R.id.preview_view)
    PreviewView mPreviewView;
    @BindView(R.id.iv_circle)
    ImageView mCircleView;
    @BindView(R.id.iv_result)
    ImageView mResultView;
    @BindView(R.id.detect_result)
    ImageView mDetectView;
    private int Id = 0;

    private DetectPresenter mPresenter;

    private boolean mUpload = false;
    private boolean mRunning = true;
    private ChooseConfigDialog mDialog;
    private void dialog(String content){
        mDialog = new ChooseConfigDialog(FaceDetectActivity.this, content);
        mDialog.show();
        mDialog.setOnClickLinstener(new ChooseConfigDialog.OnClickLinstener() {
            @Override
            public void onConfig(String mContent) {
                mDialog.dismiss();
                if(mContent.equals("1")){
                    finish();
                }

            }
        });
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if(mDialog!=null&&mDialog.isShowing()){
                return true;
            }
            dialog("退出，检测流程全部终止");
        }
        return true;

    }


    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStausBar(getResources().getColor(R.color.black));
        start();
        mPresenter = new DetectPresenter(this);
        Animation rotate = AnimationUtils.loadAnimation(this, R.anim.rotate);
        if (rotate != null) {
            mCircleView.startAnimation(rotate);
        }
    }

    private void start() {
        mPreviewView.postDelayed(new Runnable() {
            @Override
            public void run() {
                mPreviewView.start();
                setAutoTakePictureProcess();
            }
        }, 3000);

    }


    private ArrayList<Bitmap> facesBitmap;

    public List<DetectResultModel> onDetectBitmap(Bitmap bitmap1) {
        final Bitmap tmpBmp = bitmap1.copy(Bitmap.Config.RGB_565, true);
        List<DetectResultModel> list = new ArrayList();
        if (Constant.SHOW_DETECT_BITMAP) {
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Glide.with(FaceDetectActivity.this).load(tmpBmp).into(mDetectView);
                }
            });
        }
        try {
            FaceDetector faceDetector = new FaceDetector(tmpBmp.getWidth(), tmpBmp.getHeight(), 10);
            FaceDetector.Face[] face = new FaceDetector.Face[10];
            faceDetector.findFaces(tmpBmp, face);
            for (int i = 0; i < 10; i++) {
                if (face[i] != null) {
                    PointF mid = new PointF();
                    face[i].getMidPoint(mid);
                    float eyesDis = face[i].eyesDistance();
                    float confidence = face[i].confidence();
                    float pose = face[i].pose(android.media.FaceDetector.Face.EULER_Y);
                    int idFace = Id;

                    Rect rect = new Rect(
                            (int) (mid.x - eyesDis * 1.20f),
                            (int) (mid.y - eyesDis * 0.55f),
                            (int) (mid.x + eyesDis * 1.20f),
                            (int) (mid.y + eyesDis * 1.85f));

                    /**
                     * Only detect face size > 100x100
                     */
                    if (rect.height() * rect.width() > 0) {
                        if (idFace == Id) Id++;
                        FaceResult result = new FaceResult();
                        result.setFace(idFace, mid, eyesDis, confidence, pose, System.currentTimeMillis());

                        //
                        // if focus in a face 5 frame -> take picture face display in RecyclerView
                        // because of some first frame have low quality
                        //
                        final Bitmap faceCroped = ImageUtils.cropFace(result, tmpBmp, 0);
                        if (Constant.SHOW_DETECT_BITMAP) {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    Glide.with(FaceDetectActivity.this).load(faceCroped).into(mResultView);
                                }
                            });
                        }
                        if (faceCroped != null && !mUpload) {
                            final String path = Constant.SD_TEMP_IMAGE + System.currentTimeMillis() + ".jpg";
                            Utils.saveBitmap(path, tmpBmp);
                            mUpload = true;
                            mPresenter.uploadFacePic(path);
                        }
                    }
                }
            }
        } catch (Exception e) {
            return null;
        }
        return list;
    }
    private Handler handler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            Bitmap bitmap= (Bitmap) msg.obj;
//            mDetectView.setImageBitmap(bitmap);
//            Glide.with(FaceDetectActivity.this).load(bitmap).into(mDetectView);
            if (!mUpload) {
                final String path = Constant.SD_TEMP_IMAGE + System.currentTimeMillis() + ".jpg";
                Utils.saveBitmap(path, bitmap);
                mUpload = true;
                mPresenter.uploadFacePic(path);
            }

        }
    };

    private void setAutoTakePictureProcess() {
        ThreadPoolManager.execute(new Runnable() {
            @Override
            public void run() {
                while (mRunning) {
                    synchronized (this) {
                        mPreviewView.takePicture(new CameraListener.takePictureListener() {
                            @Override
                            public void onTakenPicture(Bitmap bitmap) {

                                Message message=Message.obtain();
                                message.obj=bitmap;
                                handler.sendMessage(message);
//                                if (!mUpload) {
//                                    resolveDetectResult(bitmap);
//                                }
                            }
                        });
                    }
                    try {
                        Thread.sleep(3000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private List<DetectResultModel> resolveDetectResult(Bitmap bitmap) {
        List<DetectResultModel> models = onDetectBitmap(bitmap);
        if (models == null) {
            return null;
        }
//        detectResultModelCache = models;
        return models;
    }

    @Override
    public Activity getContext() {
        return this;
    }

    @Override
    public void onRequestSuccess(List<DetectQuestion> detectQuestions) {
        startActivity(new Intent(this, FaceDetectDemoActivity.class)
                .putExtra("step", 1));
        finish();
    }

    @Override
    public void onRequestNoData(String message) {
        mUpload = false;
    }

    @Override
    public void onRequestError(String error_message) {
        mUpload = false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mRunning = false;
        if (mPreviewView != null) mPreviewView.destory();
        if (mPresenter != null) mPresenter.detachView();
    }

    @Override
    public int getLayoutResource() {
        return R.layout.activity_face_detect;
    }
}
